package de.hwrberlin.remo.diagram.custom.actions;

import java.util.List;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ListDialog;

import de.hwrberlin.remo.export.ModelExporter;
import de.hwrberlin.remo.export.ModelExporterRegistry;
import de.hwrberlin.remo.export.ModelExporterXP;

public class ExportRulesAction extends AbstractRemoDiagramAction {

	@Override
	public void run(IAction action) {
		List<ModelExporterXP> modelExporters = ModelExporterRegistry.getRegisteredModelExporters();
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		
		if(modelExporters != null && !modelExporters.isEmpty()) {
			ListDialog dialog = new ListDialog(shell);
			dialog.setTitle("Model Export");
			dialog.setMessage("Select a model exporter:");
			
			dialog.setContentProvider(new ArrayContentProvider());
			dialog.setLabelProvider(labelProvider);
			dialog.setInput(modelExporters);
			
			if(dialog.open() == Dialog.OK) {
				Object[] result = dialog.getResult();
				
				if(result.length > 0) {
					ModelExporterXP selectedExporterXP = (ModelExporterXP) result[0];
					ModelExporter exporter = selectedExporterXP.getExporter();
					
					if(exporter != null) {
						exporter.exportKnowledgeBase(modelFilePath, knowledgeBase);
					}
				}
			}
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		// Do nothing
	}
	
	private LabelProvider labelProvider = new LabelProvider() {
		@Override
		public String getText(Object element) {
			if(element != null && element instanceof ModelExporterXP) {
				ModelExporterXP exporterXP = (ModelExporterXP) element;
				String name = exporterXP.getName();
				
				if(name != null && name.length() > 0) {
					return name;
				}
			}
			
			return super.getText(element);
		};
	};
}